package com.code.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.code.springboot3.common.BusinessException;
import com.code.springboot3.mapper.ArticleMapper;
import com.code.springboot3.mapper.BigUserMapper;
import com.code.springboot3.mapper.CategoryMapper;
import com.code.springboot3.model.dto.AddCategoryDto;
import com.code.springboot3.model.dto.UpdateCategoryDto;
import com.code.springboot3.model.entity.Article;
import com.code.springboot3.model.entity.Category;
import com.code.springboot3.model.vo.CategoryVo;
import com.code.springboot3.service.CategoryService;

import com.code.springboot3.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Soft
 * @description 针对表【category】的数据库操作Service实现
 * @createDate 2024-12-26 14:20:41
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private BigUserMapper bigUserMapper;

    @Override
    public void addCategory(AddCategoryDto addCategoryDto, String token) {
        Map<String, Object> map = JwtUtil.verifyToken(token);

        Integer id = (Integer) map.get("id");
        if (id == null || id == 0) {
            throw new BusinessException("添加分类失败");
        }
        Category category = new Category();
        category.setCategoryName(addCategoryDto.getCategoryName());
        category.setCategoryAlias(addCategoryDto.getCategoryAlias());
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        category.setCreateUser(id);
        int insert = categoryMapper.insert(category);
        if (insert <= 0) {
            throw new BusinessException("添加分类失败");
        }

    }

    @Override
    public List<CategoryVo> queryCategoryList() {
        List<Category> categories = categoryMapper.selectList(new QueryWrapper<>());
        List<CategoryVo> categoryVos = new ArrayList<>();
        for (Category category : categories) {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            categoryVos.add(categoryVo);
        }
        return categoryVos;
    }

    @Override
    public void updateCategory(UpdateCategoryDto updateCategoryDto, String token) {
        Map<String, Object> map = JwtUtil.verifyToken(token);

        Integer id = (Integer) map.get("id");
        Category category = categoryMapper.selectById(updateCategoryDto.getId());
        if (category == null) {
            throw new BusinessException("更新失败，ID错误");
        }
        if (!Objects.equals(category.getCreateUser(), id)){
            throw new BusinessException("此分类，无权限修改，不是你创建的");
        }
        category.setCategoryName(updateCategoryDto.getCategoryName());
        category.setCategoryAlias(updateCategoryDto.getCategoryAlias());
        category.setUpdateTime(new Date());
        int update = categoryMapper.updateById(category);
        if (update <= 0) {
            throw new BusinessException("更新失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategory(Integer id, String token) {
        // 1. 验证分类是否存在
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }

        // 2. 验证用户权限
        Map<String, Object> claims = JwtUtil.verifyToken(token);
        Integer userId = (Integer) claims.get("id");
        if (!Objects.equals(category.getCreateUser(), userId)) {
            throw new BusinessException("无权删除此分类");
        }

        // 3. 检查分类下是否有文章
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getCategoryId, id);
        long count = articleMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("该分类下还有文章，不能删除");
        }

        // 4. 删除分类
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            throw new BusinessException("删除分类失败");
        }

    }
}




